(($) -> 
	jQuery.fn.dropdown = ->
		$statusSor = $('''
		<select style="display: none">

		</select>
		''')

		statusOptions = $('''
		<option value="open"> open </option>
		<option value="stall"> stalled </option>
		<option value="resolve"> resolved </option>
		<option value="kill" disabled='disabled'> dead </option>
		''')

		areaOptions = $('''
		<option> None </option>
		<option>Declined</option>
		<option>Inquiries</option>
		<option>Interview Requested</option>
		<option>Placed - Admin</option>
		<option>Placed - CC</option>
		<option>Placed - PA</option>
		<option>Placed - US/UT</option>
		<option>Staff Requests</option>
		''')

		$editBtn = $('''
			<div id='edit' style='position: absolute; display: table; text-align: right; color: RED; margin-top: -2px;'>
				<font style='font-size: 15px;'>
					[Edit]
				</font>
			</div>
		''')

		$subjInput = $('''
		<p style="display: none" id="genTextWrap">
			<input type="text" id="genTextArea"/>
			<br />
			<input type="submit" class="saveBtn" value="Save" />
			<input type="submit" class="cancelBtn" value="Cancel">
		</p>
		''')

		# Tooltip definitions for Status
		$statusTltip = $('''
		<div id="statusTip" class="tooltip">
			change to a different status.
		</div>
		''')

		# Tooltip definitions for Subject
		$subjectTltip = $('''
		<div id="subjectTip" class="tooltip">
			change to a different subject.
		</div>
		''')

		# Tooltip definitions for Area
		$areaTltip = $('''
		<div id="areaTip" class="tooltip">
			change to a different area.
		</div>
		''')

		# Tooltip definitions for Requestor email address
		$emailTltip = $('''
		<div id="emailTip" class="tooltip">
			change to a different email address.
		</div>
		''')
		
		# Define useful CSS objects for debugging navigation
		markCSS =
			'border-color': 'transparent'
			'border-style': 'solid'
		unmarkCSS = 
			'border-color': 'none' 
			'border-style': 'none'

		Deep = true

		# Define a regex to match a ticket's serial number
		serialNum = /serial_num=(\d+)/
		rt_link = "/rt/webrt.cgi"

		# Control flag that sets condition to displaying forms
		ctrlFlag = false
		hoverFlag = false

		# This function will serve a debugger for now because using alert method to quick debug is starting to
		# to get pretty annoying. Eventually this can be rewritten to be a tooltip implementation.
		#
		###
		dbg = (msg) ->
			target = $('#msgDisplay > font')
			$('#msgDisplay').css('top' : window.pageYOffset)
			$('#msgDisplay').css('width' : window.innerWidth)
			target.delay(100).hide(0).text(msg).fadeIn(200)
			return
		###

		# Let's adorn each table row with a class name and a serial number.
		$('font >table >tbody >tr').each ->
			$this = $(@)
			href = $('a', $this).attr 'href'
			if (href.match serialNum)?[1]
				$('#status, #area', $this).addClass('dropDownCell')

		# Status: If the user mouse-clicks a status element, we will show a
		# selection of status values.  If the user clicks out, we will replace
		# it with the original element.
		$('tbody').on 'click', '.dropDownCell', ->

			ctrlWidth = $(@).width()
			ctrlHeight = $(@).height()
			columnType = $(@).attr('id')
			# Get the serial number of the current selected ticket to be operated
			# Since each tr has a ticket id, the parentNode id gives the serial number (or ticket)
			sn = this.parentNode.id

			# Check to see if this control flag is marked. If True, then there is always a modifying control
			# somewhere on this page, so don't do anything. If false, then add the controls. 
			if !ctrlFlag

				ctrlFlag = true

				# Get the currently displayed value of the status to determine what
				# selection should be shown on the dropdown selector
				switch $(@).children('font').text()
					when 'resolved' then currentValue = 'resolve'
					when 'stalled' then currentValue = 'stall'
					else currentValue = $(@).children('font').text()


				switch columnType
					when 'status' then newOptions = statusOptions.clone()
					when 'area' 
						newOptions = areaOptions.clone()
						if currentValue.length != 1 then currentValue = currentValue.substr(0, currentValue.length - 1)
					else

				cellPos = $(@).position()

				# Since we've added a control, set the control flag to true in order to restrict
				# any more controls to be added on to the webpage
				$statusVal = $(@).children().clone Deep
				$(@).empty().append $statusSor.clone()

				$(@).children('SELECT').append newOptions

				#target = $(@).children('SELECT')
				#centerVer = cellPos.top + ctrlHeight / 2 - target.height() / 2
				#$(@).children('SELECT').css('position' : 'absolute', 'top' : centerVer)


				# Set the default option to what the current status is and then animate-show
				$(@).children('SELECT').children("OPTION:contains(#{currentValue})").attr("selected":"selected")

				$(@).children('SELECT').show 100
				
				# Focus the selector to control how to activate and deactivate the selector pulldown
				$(@).children('SELECT').focus()

				# When the selected option changes, perform HTTP_GET to server in order to set change
				$(@).change ->
					$().dbg 'Waiting for server response..'

					# Get what the user has just selected from the dropdown
					$statusVal.text("#{selected = $(@).children()[0].value.toString()} [..]")


					switch columnType
						when 'status'
							# Send HTTP_GET to parse the data
							$.get rt_link, { serial_num : sn, do_req_status : selected}, (data) ->

								exp = /Request #.* has been (opened|stalled|resolved)/
								$('#hiddenWrapper').html "<font> #{s = data.match(exp)[0].toString()} </font>"
								$().dbg s

								r = s.match(/(opened|resolved|stalled)/gi)[0]
								if r == 'opened' then r = 'open'
								$statusVal.text r

								return
						when 'area'
							setAreaLink = "#{rt_link}?serial_num=#{sn}&area=#{selected}&area=&do_req_area=true"
							$.get setAreaLink, (data) ->

								$statusVal.text "#{selected} "

								return
						else

					# After selection, lose the focus so the pulldown disappears
					this.childNodes[0].blur()


				$(@).on 'focusout', 'SELECT', ->
					$(@).replaceWith($statusVal)
					ctrlFlag = false
					return false

			return 

)(jQuery)
